# -*- coding:utf-8 -*-

from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, String
from sqlalchemy.orm import sessionmaker
from Slave.config.slave_config import *
from logger_config import logger_factory
from role_config import role

logger = logger_factory()

engin = None
DBSession = None
Base = declarative_base()
engine = create_engine(DATABASE_URI, echo=True)
DBSession = sessionmaker(bind=engine)


class MissionRecord(Base):
    __table_name__ = 'MFGRPA_TB_IUI_MISSION_RECORD'
    __table_args__ = {'sqlite_autoincrement': True}

    uuid = Column('UUID', String(100), primary_key=True)
    mission_key = Column('MISSIONKEY', String(100))
    update_time = Column('UPDATETIME', String(100))
    start_time = Column('STARTTIME', String(100))
    finish_time = Column('FINISHTIME', String(100))
    slave_id = Column('SLAVEID', String(100))
    status = Column('STATUS', String(100))


def create_table():
    Base.metadata.create_all(engine)


def delete_table(table):
    table.__table__.drop(engine)


def insert_lot(lot):
    session = DBSession()
    session.add(lot)
    session.commit()
    session.close()


def delete_lot(table, lotid: str):
    session = DBSession()
    delete_num = session.query(table).filter(table.lotid == lotid).delete()
    session.commit()
    session.close()


def delete_all_lot(table):
    session = DBSession()
    session.query(table).delete()
    session.commit()
    session.close()


def update_update_time(uuid, update_time):
    session = DBSession()
    mission = session.query(MissionRecord).filter(MissionRecord.uuid == uuid).first()
    if mission:
        mission.update_time = update_time
        session.commit()
    session.close()


def update_start_time(uuid, start_time):
    session = DBSession()
    mission = session.query(MissionRecord).filter(MissionRecord.uuid == uuid).first()
    if mission:
        mission.start_time = start_time
        session.commit()
    session.close()


def update_start_and_update_time(uuid, start_time, update_time, slave_id):
    session = DBSession()
    mission = session.query(MissionRecord).filter(MissionRecord.uuid == uuid).first()
    if mission:
        mission.slave_id = slave_id
        mission.start_time = start_time
        mission.update_time = update_time
        session.commit()
    session.close()


def update_status_and_finish_time(uuid, status, finish_time):
    try:
        session = DBSession()
        mission = session.query(MissionRecord).filter(MissionRecord.uuid == uuid).first()
        if mission:
            mission.finish_time = finish_time
            mission.status = status
            session.commit()
    except Exception as e:
        logger.error(e)
    finally:
        session.close()


MissionRecord = ''

insert_mission = ''
